[c++11]nullptr¶
参考:nullptr
std::nullptr是类型std::nullptr_t的空指针常量,可以转换成任何原始指针类型
之前通常使用NULL或者0来表示空指针,这有可能造成编译错误。从c++11开始推荐使用常量std::nullptr
示例一¶
void f(int *pi) {
std::cout << "Pointer to integer overload\n";
}
void f(double *pd) {
std::cout << "Pointer to double overload\n";
}
void f(std::nullptr_t nullp) {
std::cout << "null pointer overload\n";
}
int main() {
int *pi;
double *pd;
f(pi);
f(pd);
f(nullptr); // would be ambiguous without void f(nullptr_t)
// f(0); // ambiguous call: all three functions are candidates
// f(NULL); // ambiguous if NULL is an integral null pointer constant
// (as is the case in most implementations)
}
定义了三个重载函数,分别使用int/double/nullptr_t作为参数类型。如果输入0或者NULL作为参数,会存在二义性(ambiguous),因为均符合这3个重载函数
示例二¶
参考:nullptr, the pointer literal
std::nullptr能够输入模板函数,而0和NULL会发生错误
template<class F, class A>
void Fwd(F f, A a) {
f(a);
}
void g(int *i) {
std::cout << "Function g called\n";
}
int main() {
g(NULL); // Fine
g(0); // Fine
Fwd(g, nullptr); // Fine
// Fwd(g, NULL); // ERROR: No function g(int)
}